<template>
    <div>
      <form @submit.prevent="submitForm" class="custom-form">
  <p>注意图片位置在E:\MobileFile\img的批量上传的时候，成功上传的和重复的图片会自动转移到E:\MobileFile\imghave中</p>
  <input type="file" @change="handleFileChange" multiple class="custom-input" 
  placeholder="点击选择文件" />
  <el-upload
        class="upload-demo"
        drag
        action=""
        multiple
        :on-change="handleFileChange"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
  <button type="button" @click="submitFiles" class="custom-submit">提交</button>
  <div v-if="imageUrl">
      <img :src="imageUrl" alt="Uploaded Image" style="max-width: 100%; height: auto;"/>
    </div>
  <span v-if="arr.length>0" class="err-week">以下周扫描失败，请手动填写{{ this.arr}}{{ this.errstid }}</span>
  <span v-if="namearr.length>0">
      <span v-for="(item,index) in namearr" :key="index">{{item}}</span>
  </span>
</form>
      <table border="1">
        <tr>
          <th>学生姓名</th>
          <th>学号</th>
          <th>节次</th>
          <th>星期一</th>
          <th>星期二</th>
          <th>星期三</th>
          <th>星期四</th>
          <th>星期五</th>
          <th>星期六</th>
          <th>操作</th>
        </tr>
        <tr v-for="(rowData, index) in tableData.tableArr" :key="index">
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.studentName }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.studentName" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.studentId }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.studentId" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.period }}</span>
            <input v-if="rowData.isEditing" @blur="hideInput(index,rowData)" v-model="rowData.period" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.monday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.monday" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.tuesday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.tuesday" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.wednesday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.wednesday" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.thursday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.thursday" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.friday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.friday" />
          </td>
          <td>
            <span v-if="!rowData.isEditing">{{ rowData.saturday }}</span>
            <input v-if="rowData.isEditing"  @blur="hideInput(index,rowData)" v-model="rowData.saturday" />
          </td>
          <td><button @click="editRow(index)">编辑</button></td>
        </tr>
      </table>
      <button @click="uploadData">上传</button>
      <!-- <button @click="setallstid">统一修改</button> -->
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  export default {
      name: 'studentAdd',
      data() {
    return {
      selectedFiles: [],
      imageUrl: null,
      // 可以存储File对象用于其他处理
      file: null,
      formData: {
        name: '',
        image: null
      },
      tableData: {
        studentName: '',
        tableArr: []
      },
      arr:[],
      errstid:'',
      namearr:[],
    };
  },
      methods: {
        arrerrWeek(){
          console.log(this.arr)
          alert.log(this.arr+'这几周扫描失败，请手动填写')
        },
        /**
         * 上传数据
         */
        uploadData(){
          if(this.tableData.tableArr.length===0){
            alert('请先添加数据后再上传')
            return;
          }
            axios.post('api/cource/addData', this.tableData.tableArr)
        .then(response => {
             if(response.data.code===0){
              alert(response.data.msg)
             }else{

             }
           }).catch(error => {
             alert(error.data.msg);
           });
        },
        editRow(index) {
      this.tableData.tableArr[index].isEditing = true;
    },
    hideInput(index) {
      this.tableData.tableArr[index].isEditing = false;
    },
    /**
     * 处理文件
     * @param event 
     */
      //   handleFileChange(event) {
      //   this.formData.image = event.target.files[0];
      //   // this.tableData.studentName=this.formData.image.name;
      // },
      /**
       * 扫描文件
       */
       submitFiles(){
        if(this.selectedFiles.length>1){
          this.submitFiles2();
        }else{
          this.submitFiles1();
        }
       },
       submitFiles1() {
          const file = this.formData.image;
        if(file){
          const reader = new FileReader();
        reader.onload = (e) => {
          // 设置图片的URL为读取后的DataURL
          this.imageUrl = e.target.result;
        };
        reader.readAsDataURL(file);

// 存储File对象以便其他用途
this.file = file;
        }
        
            //将图片的名字赋值给tableData.studentName,去除后缀
            const nameArr=this.formData.image.name.split('.');
            this.tableData.studentName=nameArr[0];
            this.tableData.tableArr=[];
        const formData = new FormData();
        formData.append('image', this.formData.image);
        axios.post('api/cource/scanData', formData)
        .then(response => {
             const vo=response.data.data.courceVo;
             const errvo=response.data.data.errcourceVo
             if(errvo[errvo.length-1]===-1){
              response.data.data.errcourceVo.pop();
              this.errstid='学号扫描失败请统一设置'
             }
             this.arr=errvo;
            //  alert(response.data.data.errcourceVo+'这几周扫描失败，请手动填写')
             //筛选出vo中period为1的数据
             let num=1;
             while(num<6){
             const periodnum=vo.filter(item=>item.period==num);
             console.log(num)
            //将第n节的数据赋值
                const objectOne={
                    studentName: this.tableData.studentName ,
                    studentId: periodnum[0].studentId,
                    period: this.period(num),
                        monday: this.weekofday(1,periodnum),
                        tuesday: this.weekofday(2,periodnum),
                        wednesday: this.weekofday(3,periodnum),
                        thursday: this.weekofday(4,periodnum),
                        friday: this.weekofday(5,periodnum),
                        saturday: this.weekofday(6,periodnum),
                        isEditing: false
                }
                this.tableData.tableArr.push(objectOne);
                // console.log(objectOne);
             num++;
             }
             console.log(this.tableData.tableArr);
           })
        .catch(error => {
             alert(error.data.msg);
           });
      },
      /**
       * 返回例如'全(0-0)周1'的字符串
       * @param n 
       * @param period 
       */
      weekofday(n,period){
        //查询period中dayOfWeek为n的课程
        let week=period.filter(item=>item.dayOfWeek==n);
        if(week.length==0){
            return '全(0-0)周'+n;
        }else if(week.length==1){
            let all='';
        switch(week[0].weekType){
            case 0:
                all='全'
                break;
            case 1:
                all='单'
                break;
            case 2:
                all='双'
                break;
        }
        all=all+'('+week[0].start_week+'-'+week[0].end_week+')'+'周'+n;
            return all;
        }else{
            return '出现错误';
        }
      },
      /**
       * 返回第几节例如1-2节的字符串
       * @param n 
       */
      period(n){
    switch(n){
            case 1:
                return '1-2节';

            case 2:
                return '3-4节';

            case 3:
                return '5-6节';

            case 4:
                return '7-8节';
            case 5:
                return '9-10节';
        }
      },
      /************************************ */
    //   handleFileChange(event) {
    //     console.log(event)
    //     if(event.target.files.length>1){
    //       this.imageUrl=event.target.files[0].result;
    //   for (let i = 0; i < event.target.files.length; i++) {
    //     this.selectedFiles.push(event.target.files[i]);
    //   }
    //     }else if(event.target.files.length==1){
    //       this.formData.image = event.target.files[0];
    //     }

    // },
    handleFileChange(file, fileList) {
      // file 是当前变化的文件对象
      // fileList 是所有已选中的文件列表

      // 添加文件到 selectedFiles
      this.selectedFiles.push(file.raw);

      // 如果是单个文件，更新 formData
      if (fileList.length === 1) {
        this.formData.image = file.raw;
        this.previewImage(file.raw);
      } else {
        // 如果是多个文件，只显示第一个文件的预览图
        this.previewImage(fileList[0].raw);
      }
    },
    previewImage(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imageUrl = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    submitFiles2() {
      // 检查是否有文件被选中
      if (this.selectedFiles.length === 0) {
        alert('请选择文件后再提交！');
        return;
      }
      this.imageUrl=this.selectedFiles[0].result;
      // 创建一个FormData对象，以便将文件以表单数据的形式发送
      const formData = new FormData();
      for (let i = 0; i < this.selectedFiles.length; i++) {
        formData.append('files', this.selectedFiles[i]); 
      }
      console.log(formData);
      // 使用axios发送POST请求到后端
      axios.post('api/cource/allimage', formData)
      .then(response => {
        const truename= response.data.data.truenames;
        const errname=response.data.data.errnames;
        const havename=response.data.data.havenames;
        this.namearr.push('上传成功的人有：'+truename);
        this.namearr.push('上传失败的人有：'+errname);
        this.namearr.push('重复上传的人有：'+havename);
      })
      .catch(error => {
        // 处理错误
        console.error('文件上传失败:', error);
      });
    },
      },
  //     created() {
  //   this.submitForm();
  // },
  // mounted() {
  //   this.submitForm();
  // },
    }
  </script>
  
  <style scoped>
   /* .custom-form {
    display: flex;
    flex-direction: column;
    align-items: center;
  }



 .custom-submit {
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
  }

 .custom-submit:hover {
    background-color: #45a049;
  } */
   .custom-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}
  </style>